package com.earthea.application.web.controller.monitor;

import com.earthea.application.common.annotation.Log;
import com.earthea.application.common.core.domain.model.LoginUser;
import com.earthea.application.common.entity.BaseResponse;
import com.earthea.application.common.entity.TableDataInfo;
import com.earthea.application.common.enums.BusinessType;
import com.earthea.application.common.enums.CacheEnum;
import com.earthea.application.common.utils.StringUtil;
import com.earthea.application.system.domain.entity.SysUserOnline;
import com.earthea.application.system.domain.transfer.SysTransfer;
import com.earthea.cache.CacheService;
import com.earthea.common.util.JacksonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * 在线用户监控
 */
@RestController
@RequestMapping("/rest/monitor/online")
public class SysUserOnlineController {

    @Autowired
    private CacheService cacheService;

    @PreAuthorize("@ss.hasPermi('monitor:online:list')")
    @GetMapping("/list")
    public TableDataInfo<SysUserOnline> list(String ipaddr, String userName) {
        Collection<String> keys = cacheService.keys(CacheEnum.LOGIN_TOKEN.getCacheKey("*"));
        List<SysUserOnline> userOnlineList = new ArrayList<>(keys.size());
        for (String key : keys) {
            LoginUser user = JacksonUtils.fromJson(cacheService.get(key), LoginUser.class);
            if (user == null || user.getUser() == null) {
                continue;
            }
            if (StringUtils.isNotEmpty(ipaddr) && !StringUtil.equals(ipaddr, user.getIpaddr())) {
                continue;
            }
            if (StringUtils.isNotEmpty(userName) && !StringUtil.equals(userName, user.getUsername())) {
                continue;
            }
            userOnlineList.add(SysTransfer.INSTANCE.toSysUserOnline(user));
        }
        Collections.reverse(userOnlineList);
        userOnlineList.removeAll(Collections.singleton(null));
        return new TableDataInfo<>(userOnlineList.size(), userOnlineList);
    }

    /**
     * 强退用户
     */
    @PreAuthorize("@ss.hasPermi('monitor:online:forceLogout')")
    @Log(title = "在线用户", businessType = BusinessType.FORCE)
    @DeleteMapping("/{tokenId}")
    public BaseResponse forceLogout(@PathVariable String tokenId) {
        cacheService.del(CacheEnum.LOGIN_TOKEN.getCacheKey(tokenId));
        return BaseResponse.success();
    }
}
